<!-- 医院权限 -->
<template>
  <div class="ky-container">
    <div class="left-content">
      <el-card shadow="hover" class="ky-card ky-card-sx ky-card-hdbg">
        <el-form ref="formSearch" :model="formData" :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="40px">
          <el-form-item label="省" prop="provinceName">
            <el-select v-model="formData.provinceName" placeholder="请选择" @change="getCity" clearable>
              <el-option
                v-for="item in prov"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="cityName">
            <el-select v-model="formData.cityName" placeholder="请选择" @change="getDistrict" clearable>
              <el-option
                v-for="item in city"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="县" prop="county">
            <el-select v-model="formData.county" placeholder="请选择" clearable>
              <el-option
                v-for="item in district"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="hover" class="ky-card ky-card-hdbg ky-mt10">
        <el-table
          ref="table"
          v-loading="loading"
          size="medium"
          :data="tableData"
          style="width: 100%"
          max-height="578px"
          border
          class="ky-table"
          highlight-current-row
          @row-click="bindData"
        >
          <el-table-column align="left" label="操作" width="140">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center text-center">
                <el-button type="primary" size="small" @click.stop="bindData( scope.row)">权限</el-button>
                <el-button type="" size="small" @click.stop="configSet( scope.row)">配置</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="地区" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.provinceName +'-'+ scope.row.cityName + '-'+ scope.row.county}}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="医院名称" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="code" label="医院代码" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="isRemote" label="是否会诊">
            <template slot-scope="scope">
              <el-tag size="small" type="success" v-if="scope.row.isRemote">开启</el-tag>
              <el-tag size="small" type="danger" v-else>关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="是否审核">
            <template slot-scope="scope">
              <el-tag size="small" type="success" v-if="scope.row.status">启用</el-tag>
              <el-tag size="small" type="danger" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="添加时间" min-width="160"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" min-width="160"></el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="changePagination"
        />
      </el-card>
    </div>
    <div class="right-content">
      <el-card shadow="hover" class="ky-card ky-card-sm ky-card-hdbg">
        <div slot="header">医院权限{{currentRow?'【'+currentRow.name+'】':''}}</div>
        <el-tree
          v-loading="rightLoading"
          ref="tree"
          :props="props"
          :data="treeNode"
          show-checkbox
          node-key="key"
        >
        </el-tree>
        <div class="divide-line" v-show="treeNode.length>0">
          <el-button type="primary" size="small" @click="save">保存</el-button>
        </div>
      </el-card>
    </div>

    <CheckConfigSetting
      :btn-show="false"
      :hospital-code.sync="configHospitalCode"
      :config-visible.sync="configVisible"
    />
  </div>
</template>

<script>
import { getDeptList, syshospitalGetpages, gethospitaldataauthority, gethospitaldataauthoritytree, sethospitaldataauthority } from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import dealTreeUtil from '@/utils/dealTreeUtil.js'
import area from '@/data/area.json'
import CheckConfigSetting from '@/components/appConfig/check/checkRegistrationConfig'
export default {
  name: '',
  mixins: [],
  components: { paginationCont, CheckConfigSetting },
  data() {
    return {
      currentRow: null,
      formData: {
        provinceName: '',
        cityName: '',
        county: '',
        name: ''
      },
      deptCodeList: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      tableData: [],
      rightLoading: false,
      prov: [],
      city: [],
      district: [],
      props: {
        label: 'name',
        children: 'children'
      },
      treeNode: [],

      configHospitalCode: this.$store.state.user.hospitalCode,
      configVisible: false
    }
  },
  watch: {},
  computed: {},
  created() {
    this.$getHospitalList()
    this.getDeptCodeList()
    this.search()
  },
  mounted() {
    this.handleProv()
  },
  methods: {
    configSet(row) {
      console.log('configset row =', row)
      this.configHospitalCode = row.code
      this.configVisible = true
    },
    handleProv() {
      this.prov = []
      for (let i in area) {
        this.prov.push(i)
      }
      this.prov.shift()
    },
    getCity() {
      this.city = []
      this.district = []
      this.formData.county = ''
      for (let i in area[this.formData.provinceName]) {
        this.city.push(i)
      }
      this.city.shift()
      this.formData.cityName = ''
    },
    getDistrict() {
      this.district = []
      for (let i in area[this.formData.provinceName][this.formData.cityName]) {
        this.district.push(area[this.formData.provinceName][this.formData.cityName][i])
      }
      this.district.shift()
      this.formData.county = ''
    },
    sexFormatter(row, column, cellValue, index) {
      let sexName = ''
      if (row.sex === 0) {
        sexName = '其他'
      } else if (row.sex === 1) {
        sexName = '男'
      } else if (row.sex === 2) {
        sexName = '女'
      }
      return sexName
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      this.treeNode = []
      this.currentRow = null
      this.loading = true
      let params = {
        ...this.formData,
        pageNumber: this.currentPage,
        pageSize: this.pageSize
      }
      syshospitalGetpages(params).then((res) => {
        this.loading = false
        if (res && res.code == 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
        }
      })
    },
    hospitalChange() {
      this.formData.deptCode = ''
      this.getDeptCodeList()
    },
    getDeptCodeList() {
      if (this.formData.hospitalCode) {
        getDeptList({ HospitalCode: this.formData.hospitalCode }).then((res) => {
          if (res && res.code === 10000) {
            this.deptCodeList = res.content.list
          }
        })
      } else {
        this.deptCodeList = []
      }
    },
    bindData(row) {
      this.currentRow = row
      this.rightLoading = true
      this.$refs.table.setCurrentRow(row)
      Promise.all([this.getTree(row), this.getTreeData(row)]).then(() => {
        this.rightLoading = false
      }).catch(() => {
        this.rightLoading = false
      })
    },
    changePagination() {
      this.fetchData()
    },
    handleCheckChange() {

    },
    getTree(row) {
      return new Promise((rs, rj) => {
        this.treeNode = []
        gethospitaldataauthoritytree({ hospitalCode: row.code }).then((res) => {
          if (res && res.code == 10000) {
            let changeList = [
              { key: 'depAreaCheckRooms', value: 'children' },
              { key: 'depCheckRooms', value: 'children' },
              { key: 'modalityCheckRooms', value: 'children' },
              { key: 'hospitalName', value: 'name' },
              { key: 'depArea', value: 'name' },
              { key: 'dep', value: 'name' },
              { key: 'modality', value: 'name' }
            ]
            this.treeNode = dealTreeUtil.copyTransFunc(res.content.list, changeList)
            this.dealTree(this.treeNode)
          }
          rs()
        }).catch(() => {
          rj()
        })
      })
    },
    getTreeData(row) {
      return new Promise((rs, rj) => {
        gethospitaldataauthority({ hospitalCode: row.code }).then((res) => {
          if (res && res.code === 10000) {
            let list = res.content.list
            let keys = []
            list.forEach(e => {
              let k = e.hospitalCode
              if (e.depArea) {
                k = k + '-' + e.depArea
              }
              if (e.dep) {
                k = k + '-' + e.dep
              }
              if (e.modality) {
                k = k + '-' + e.modality
              }
              keys.push(k)
            })
            this.$refs.tree.setCheckedKeys(keys)
          }
          rs()
        }).catch(() => {
          rj()
        })
      })
    },
    dealTree(arr, key) {
      arr.forEach((item) => {
        if (!key) {
          item.key = item.hospitalCode
        } else {
          item.key = key + '-' + item.name
        }
        if (item.children && item.children.length) {
          this.dealTree(item.children, item.key)
        }
      })
    },
    save() {
      let keys = this.$refs.tree.getCheckedKeys()
      let savedKeys = [] // 将被保存的key
      let arr = []
      keys.forEach(k => {
        let flag = true
        for (let sk of savedKeys) {
          if (k.indexOf(sk) > -1) { // 比较是否有父级被保存过-父级被保存过这一级就不给保存了
            flag = false
            return
          }
        }
        if (flag) {
          savedKeys.push(k)
          let obj = {
            hospitalCode: k.split('-')[0],
            depArea: k.split('-')[1],
            dep: k.split('-')[2],
            modality: k.split('-')[3]
          }
          arr.push(obj)
        }
      })
      this.rightLoading = true
      sethospitaldataauthority({ sysHospitalCode: this.currentRow.code, list: arr }).then((res) => {
        this.rightLoading = false
        if (res && res.code) {
          this.$message.success('保存成功')
        }
      }).catch(() => {
        this.rightLoading = false
      })
    }
  },
  beforeDestroy() {},
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.ky-container{
    .left-content{
        width: calc(100% - 360px);
        float: left;
    }
    .right-content{
        width: 350px;
        float: left;
        margin-left: 10px;
        .el-tree{
            height: calc(100vh - 192px);
            overflow-y: auto;
        }
        .ky-card{
            height: 100%;
        }
        .divide-line{
            width:100%;
            border-top: 1px solid #e5e5e5;
            min-height: 40px;
            padding-top: 10px;
            text-align: right;
        }
    }
}
.ky-form-inline-sm .el-form-item /deep/ .el-input__inner{
    width: 220px;
}
</style>
